package com.boby.homecamera.helper

import android.Manifest
import androidx.annotation.RequiresPermission
import java.util.concurrent.LinkedBlockingQueue


class AudioRecoderHelper(private val audioDataCallBack:(ByteArray) -> Unit) {
   private var audioSender:AudioSender? = null
    private var sendBytesThread:Thread? = null
    private var isStart = false
    private var audioDataBytesQueue = LinkedBlockingQueue<ByteArray>(30)

    @RequiresPermission(Manifest.permission.RECORD_AUDIO)
    fun start() {
        if(audioSender != null){
            return
        }
        audioSender = AudioSender({
//            audioDataBytesQueue.put( it)
            audioDataBytesQueue.offer( it)
        })
        audioSender?.start()
        isStart = true
        sendBytesThread = Thread{
            while (isStart){
                try {
                    val data = audioDataBytesQueue.take()
                    audioDataCallBack.invoke(data)
                }catch (e: Exception){
                    e.printStackTrace()
                }
            }
        }.apply {
            start()
        }
    }


    fun stop() {
        isStart = false
        audioSender?.stop()
        try {
            sendBytesThread?.interrupt()
        }catch (e: Exception){
            e.printStackTrace()
        }
        sendBytesThread = null

    }
}